package com.tql.mall.cart.controller;

import com.tql.mall.cart.service.CartService;
import com.tql.mall.common.result.R;
import com.tql.mall.common.util.AuthContextHolder;
import com.tql.mall.model.cart.CartInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author: tyk
 * @Date: 2023/5/25 19:42
 * @Description:
 */
@RestController
@RequestMapping("api/cart")
@Api("购物车管理")
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 添加到购物车
     */
    @GetMapping("addToCart/{skuId}/{skuNum}")
    @ApiOperation("添加到购物车")
    public R<Void> addToCart(@PathVariable Long skuId,
                             @PathVariable Integer skuNum,
                             HttpServletRequest req) {
        // 获取用户ID
        String userId = getUserId(req);

        // 加入购物车
        cartService.addToCart(skuId, skuNum, userId);

        return R.ok();
    }


    /**
     * 查询购物车
     */
    @GetMapping("cartList")
    @ApiOperation("查询购物车")
    public R<List<CartInfo>> cartList(HttpServletRequest req) {

        // 用户ID
        String userId = AuthContextHolder.getUserId(req);
        String userTempId = AuthContextHolder.getUserTempId(req);

        // 查询购物车
        List<CartInfo> cartInfoList = cartService.cartList(userId, userTempId);

        return R.ok(cartInfoList);
    }

    /**
     * 更新选中状态
     */
    @GetMapping("checkCart/{skuId}/{isChecked}")
    @ApiOperation("更新选中状态")
    public R<Void> checkCart(@PathVariable Long skuId,
                       @PathVariable Integer isChecked,
                       HttpServletRequest req) {
        // 获取用户ID
        String userId = getUserId(req);
        // 选中选中状态变更
        cartService.checkCart(userId, skuId, isChecked);
        return R.ok();
    }


    /**
     * 删除购物车
     */
    @DeleteMapping("deleteCart/{skuId}")
    @ApiOperation("删除购物车")
    public R<Void> deleteCart(@PathVariable Long skuId,
                        HttpServletRequest req) {
        // 用户ID
        String userId = getUserId(req);
        // 删除购物车
        cartService.deleteCart(userId, skuId);
        return R.ok();
    }

    /**
     * 删除所选中的商品
     */
    @DeleteMapping("deleteChecked")
    @ApiOperation("删除所选中的商品")
    public R<Void> deleteChecked(HttpServletRequest req) {
        // 删除所选商品
        cartService.deleteChecked(getUserId(req));
        return R.ok();
    }

    /**
     * 从请求中获取用户ID或临时用户ID
     */
    private String getUserId(HttpServletRequest req) {
        // 仅当用户ID为空时才使用临时用户ID
        String userId = AuthContextHolder.getUserId(req);
        if (StringUtils.isEmpty(userId))
            userId = AuthContextHolder.getUserTempId(req);
        return userId;
    }

}
